package com.hyh.ad.common.utils.zip;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipFileUtil {

    /**
     * 创建一个包含指定文件的ZIP文件。
     *
     * @param fileNames 需要压缩的文件路径数组
     * @return 包含ZIP文件内容的ByteArrayOutputStream
     * @author hyh
     * @throws IOException 如果在读取文件或创建ZIP时发生I/O错误
     */
    public ByteArrayOutputStream createZipFile(String[] fileNames) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zipOut = new ZipOutputStream(baos)) {
            for (String fileName : fileNames) {
                // 从 static 目录加载文件
                String filePath = "admin/src/main/resources/static/uploads/" + fileName;
                File fileToZip = new File(filePath);
                if (!fileToZip.exists()) {
                    throw new IOException("File not found: " + fileToZip.getAbsolutePath());
                }

                try (FileInputStream fis = new FileInputStream(fileToZip)) {
                    ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
                    zipOut.putNextEntry(zipEntry);

                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                }
            }
        }
        return baos;
    }
}
